JS 找出两个数组中的交集

标签:2023-07-03 09:22:25

1、方法一(常规for循环)

两个数组进行for循环嵌套,然后判断元素是否相等,如果相等就push到新的数组中。

let arr1 = [1, 2, 3, 4, 5]
let arr2 = [4, 5, 6, 7, 8]
let intersection = []

for (let i = 0; i < arr1.length; i  ) {
  for (let j = 0; j < arr2.length; j  ) {
    if (arr1[i] === arr2[j]) {
      intersection.push(arr1[i])
    }
  }
}
console.log(intersection) // [4, 5]

方法二(使用ES6的filter函数和includes函数)

let arr1 = [1, 2, 3, 4, 5]
let arr2 = [4, 5, 6, 7, 8]
console.log(arr1.filter((item) => arr2.includes(item))) // [4, 5]

方法三(reduce)

先合并和排序,然后通过reduce参数进行对比,判断上一个和当前元素相同时push到新的数组中。

let arr1 = [1, 2, 3, 4, 5]
let arr2 = [4, 5, 6, 7, 8]
let arr = arr1.concat(arr2).sort()
let intersection = []

arr.reduce((pre, now) => {
  if (pre === now) {
    intersection.push(now)
  }
  return now
})
console.log(intersection) // [4, 5]
原文出处:http://www.dongblog.com/notes/31.html
来源:博客网 转载请注明出处!

活跃用户

2154919106
Ta还没有签名
总要做点实事儿
Ta还没有签名
后端程序员
Ta还没有签名
清醒一点
Ta还没有签名

友情链接


Warning: Smarty error: unable to read resource: "../../../templates/default/./common/foot/footer_index.htm" in /usr/home/hyu3925200001/htdocs/common/smarty/Smarty.class.php on line 1093

Warning: Smarty error: unable to read resource: "../../../templates/default/./common/foot/footer_index.htm" in /usr/home/hyu3925200001/htdocs/common/smarty/Smarty.class.php on line 1093